import pandas as pd
import xmind
import os


def excel_to_xmind(excel_file, xmind_file):
    try:
        # 读取 Excel 文件
        df = pd.read_excel(excel_file)
        print("成功读取 Excel 文件")

        # 检查 XMind 文件是否存在，如果不存在则创建新的工作簿
        if not os.path.exists(xmind_file):
            workbook = xmind.new()
            print("创建新的 XMind 工作簿")
        else:
            workbook = xmind.load(xmind_file)
            print("成功加载 XMind 文件")

        sheet = workbook.getPrimarySheet()
        root_topic = sheet.getRootTopic()
        root_topic.setTitle("测试用例")

        # 按目录分组
        grouped = df.groupby(df.columns[1])

        for directory, group in grouped:
            # 创建目录主题
            directory_topic = root_topic.addSubTopic()
            directory_topic.setTitle(directory)

            for index, row in group.iterrows():
                # 创建标题主题
                title = f"tc-p1-功能测试:{row[df.columns[0]]}"
                title_topic = directory_topic.addSubTopic()
                title_topic.setTitle(title)

                # 创建前置条件主题
                precondition = f"pc:{row[df.columns[2]]}"
                precondition_topic = title_topic.addSubTopic()
                precondition_topic.setTitle(precondition)

                # 处理步骤描述和预期结果
                steps = row[df.columns[3]]
                expected_results = row[df.columns[4]]

                if isinstance(steps, str) and isinstance(expected_results, str):
                    step_list = steps.split("【")
                    result_list = expected_results.split("【")

                    for i in range(1, min(len(step_list), len(result_list))):
                        step = step_list[i].split("】")[1].strip()
                        result = result_list[i].split("】")[1].strip()

                        # 创建步骤主题
                        step_topic = title_topic.addSubTopic()
                        step_topic.setTitle(step)

                        # 创建预期结果主题
                        result_topic = step_topic.addSubTopic()
                        result_topic.setTitle(result)

        # 保存 XMind 文件
        xmind.save(workbook, path=xmind_file)
        print("成功保存 XMind 文件")
    except Exception as e:
        print(f"发生错误: {e}")


if __name__ == "__main__":
    excel_path = "C:\\Users\\leixin\\Downloads\\7代起爆器APP-导出用例-20250427140747.xlsx"
    xmind_path = "C:\\Users\\leixin\\Downloads\\1.xmind"
    excel_to_xmind(excel_path, xmind_path)